<?php

namespace Biz\service\activity;

use Biz\cache\activity\Topic;
use Biz\cache\wiki\TopicWiki;
use Biz\model\activity\Page as mPage;
use Biz\model\activity\PageModule;
use Biz\model\activity\PageModule as mPageModule;
use Biz\model\activity\PageModuleArticle as mPageModuleArticle;
use Biz\model\activity\PageModuleGoods as mPageModuleGoods;
use Biz\model\activity\PageModuleH5Obj;
use Biz\model\activity\PageModuleImg as mPageModuleImg;
use Biz\model\activity\PageModuleWiki as mPageModuleWiki;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\service\Goods;
use Biz\service\wiki\Wiki;
use Biz\tools\BizUrl;
use Biz\cache\brand\BrandBeLikedache;
use Doraemon\cache\UserCounter;
use Doraemon\model\Member;
use Doraemon\service\Content\AdmContent;
use Doraemon\service\es\EsPhoto;
use Doraemon\service\Follow;
use Doraemon\service\Photos;
use Doraemon\tools\BlockType;
use Doraemon\tools\BlockTypeMapping;
use Doraemon\tools\IdParse;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\LinkFormat;
use Doraemon\tools\StatSign;

/**
 * @deprecated
 */
class Page
{

    const COUPON_TAG_NONE = 0;//无状态
    const COUPON_TAG_RECEIVED = 1;//已领取
    const COUPON_TAG_OVER = 2;//已抢光


    const THE_PARAGRAPH_PAGE_GOODS = 6;
    protected static $floatBgColor = '#2DB7B5';

    public static function getPageInfo($pageId, $isPreview = false, $date = "", $uid = 0)
    {
        if (!$isPreview) {
            $date = date('Y-m-d H:i:s');
        }
        $pageInfo = mPage::getPageInfoById($pageId);

        if ($pageInfo) {
            if (!$isPreview) {
                if ($pageInfo['status'] != mPage::STATUS_NORMAL) {
                   throw new \Exception('活动已结束');
                }
                if ($pageInfo['start_time'] > $date) {
                    throw new \Exception('活动尚未开始');
                }
                if ($pageInfo['end_time'] < $date) {
                    throw new \Exception('活动已结束');
                }
            }
            //关联的活动id
            $relationPageIds = $pageInfo['relation_id_array'];
            $relationPageInfo = [];
            if (!empty($relationPageIds)) {
                $rs = mPage::getList([
                    'id' => $relationPageIds,
                    'status' => mPage::STATUS_NORMAL,
                    'start_time[<=]' => $date,
                    'end_time[>=]' => $date
                ]);
                $map = array_column($rs, null, 'id');
                foreach ($relationPageIds as $v) {
                    if (isset($map[$v])) {
                        $relationPageInfo[] = $map[$v];
                    }
                }
            }
            $pageIds = empty($relationPageInfo) ? [] : array_column($relationPageInfo, 'id');
            array_push($pageIds, $pageId);


            //模块列表
            $pageModules = mPageModule::getModuleListByPageId($pageIds, $date);
            $goodsModuleIds = [];
            $imgModuleIds = [];
            $wikiModuleIds = [];
            $articleModuleIds = [];
            $specialModuleIds = [];
            $cplMouduleIds = [];


            $selfPageModules = [];
            foreach ($pageModules as $pageModule) {
                if ($pageModule['page_id'] == $pageId) {
                    switch ($pageModule['type']) {
                        case mPageModule::MODULE_TYPE_IMG:
                        case mPageModule::MODULE_TYPE_CARD_BANNER:
                            $imgModuleIds[] = $pageModule['id'];
                            break;
                        case mPageModule::MODULE_TYPE_GOODS:
                        case mPageModule::MODULE_TYPE_SPECIAL_GOODS:
                            $goodsModuleIds[] = $pageModule['id'];
                            break;
                        case mPageModule::MODULE_TYPE_WIKI:
                            $wikiModuleIds[] = $pageModule['id'];
                            break;
                        case mPageModule::MODULE_TYPE_CARD_ARTICLE:
                        case mPageModule::MODULE_TYPE_CARD_WATERFALL:
                            $articleModuleIds[] = $pageModule['id'];
                            break;
                        case mPageModule::MODULE_TYPE_SPECIAL_ARTICLE:
                        case mPageModule::MODULE_TYPE_SPECIAL_NOTE:
                            $specialModuleIds[] = $pageModule['id'];
                            break;
                        case mPageModule::MODULE_TYPE_CPL:
                            $cplMouduleIds[] = $pageModule['id'];
                            break;


                    }
                    $selfPageModules[] = $pageModule;
                } else {//关联活动id
                    if ($pageModule['type'] == mPageModule::MODULE_TYPE_GOODS) {
                        $goodsModuleIds[] = $pageModule['id'];
                    }
                }
            }


            $moduleImgs = empty($imgModuleIds) ? [] : mPageModuleImg::getImgByModuleId($imgModuleIds);
            $moduleGoods = empty($goodsModuleIds) ? [] : mPageModuleGoods::getGoodsByModuleId($goodsModuleIds, false);
            $moduleWikis = empty($wikiModuleIds) ? [] : mPageModuleWiki::getWikiByModuleId($wikiModuleIds, false);
            $moduleArticles = empty($articleModuleIds) ? [] : mPageModuleArticle::getArticleByModuleId($articleModuleIds,
                false);
            $moduleSpecials = empty($specialModuleIds) ? [] : PageModuleH5Obj::getArticleByModuleId($specialModuleIds,
                false);
            $moduleCpls = empty($cplMouduleIds) ? [] :CplRecord::getFormatedRecordByModuleIds($cplMouduleIds , $uid);

            return self::formatPage($pageInfo, $selfPageModules, $moduleImgs, $moduleGoods, $moduleWikis,
                $moduleArticles, $moduleSpecials, $uid, $relationPageInfo ,$moduleCpls);
        } else {
            throw new \Exception('活动不存在');
        }
    }

    public static function getPageGoods($pageIds)
    {
        $date = date('Y-m-d H:i:s');
        $pageInfos = empty($pageIds) ? [] : mPage::getValidPagesByPageIds($pageIds);
        $validPageIds = empty($pageInfos) ? [] : array_column($pageInfos, 'id');
        $pageModules = $validPageIds ? mPageModule::getModuleListByPageId($validPageIds, $date) : [];
        $pageModules = empty($pageModules) ? [] : $pageModules;
        $pageGoodsModuleIds = [];
        $goodsModuleIds = [];
        foreach ($pageModules as $pageModule) {
            if ($pageModule['type'] == mPageModule::MODULE_TYPE_GOODS) {
                $pageGoodsModuleIds[$pageModule['page_id']][] = $pageModule['id'];
                $goodsModuleIds[] = $pageModule['id'];
            }
        }
        $moduleGoods = empty($goodsModuleIds) ? [] : mPageModuleGoods::getGoodsByModuleId($goodsModuleIds);
        $moduleGoodsList = [];
        foreach ($moduleGoods as $moduleGood) {
            $moduleGoodsList[$moduleGood['module_id']][] = $moduleGood['goods_id'];
        }
        $formatPageGoods = [];
        foreach ($pageInfos as $pageInfo) {
            $goods = [];
            $goodsInfos = [];
            if (isset($pageGoodsModuleIds[$pageInfo['id']])) {
                foreach ($pageGoodsModuleIds[$pageInfo['id']] as $moduleId) {
                    $goods = array_merge($goods, $moduleGoodsList[$moduleId] ?: []);
                }
                if ($goods) {
                    $goodsInfos = Goods::Goods(array_slice($goods, 0, self::THE_PARAGRAPH_PAGE_GOODS));
                }
            }
            $formatPageGoods[$pageInfo['id']] = [
                'id' => $pageInfo['id'],
                'title' => $pageInfo['title'],
                'link' => BizUrl::formatUrlByClientType(BizUrl::h5ActivityPage($pageInfo['id'])),
                'sub_title' => $pageInfo['sub_title'],
                'icon_url' => $pageInfo['icon_url'],
                'goods' => array_values($goodsInfos)
            ];
        }
        return $formatPageGoods;
    }

    private static function formatPage(
        $pageInfo,
        $pageModules,
        $moduleImgs,
        $moduleGoods,
        $moduleWikis,
        $moduleArticles,
        $moduleSpecials,
        $uid,
        $relationPageInfo,
        $moduleCpls
    )
    {

        $response = [
            'id' => $pageInfo['id'],
            'page_type' => $pageInfo['page_type'],
            'title' => $pageInfo['title'],
            'bgcolor' => $pageInfo['bgcolor'],
            'icon' => $pageInfo['icon_url'],
        ];
        $response['share_info'] = self::formatShareInfo($pageInfo);
        $goodsIds = empty($moduleGoods) ? [] : array_column($moduleGoods, 'goods_id');
        $goodsInfos = Goods::Goods($goodsIds);

        $wikiIds = empty($moduleWikis) ? [] : array_column($moduleWikis, 'wiki_id');

        $wikiInfos = Wiki::getWikiList($wikiIds);

        //格式化商品模块数据
        $moduleGoodsMap = [];
        $pageModuleGoodsMap = [];
        if ($moduleGoods) {
            foreach ($moduleGoods as $v) {
                if ($v['page_id'] == $pageInfo['id']) {
                    $pageModuleGoodsMap[$v['module_id']][] = $v;
                } else {
                    $moduleGoodsMap[$v['page_id']][] = $v;
                }
            }
        }

        //格式化wiki模块数据
        $moduleWikisMap = [];
        $pageModuleWikisMap = [];
        if ($moduleWikis) {
            foreach ($moduleWikis as $v) {
                if ($v['page_id'] == $pageInfo['id']) {
                    $pageModuleWikisMap[$v['module_id']][] = $v;
                } else {
                    $moduleWikisMap[$v['page_id']][] = $v;
                }
            }
        }


        //格式化图片模块数据
        $moduleImgsMap = [];
        foreach ($moduleImgs as $v) {
            $moduleImgsMap[$v['module_id']][] = $v;
        }


        //格式化h5榜单卡片模块数据
        $moduleSpecialMap = [];
        if ($moduleSpecials) {
            $contentMap = [];
            foreach ($moduleSpecials as $key => $item) {
                $objId = $item['obj_id'];
                $objType = IdParse::getType($objId);
                $contentMap[$objType][] = $objId;
            }
            foreach ($contentMap as $article_type => $aids) {
                $contentMap[$article_type] = AdmContent::dynamic($article_type, $aids, $uid);
            }
            foreach ($moduleSpecials as $v) {
                $objId = $v['obj_id'];
                $objType = IdParse::getType($objId);
                $contentList = $contentMap[$objType] ?? [];
                if (isset($contentList[$objId])) {
                    $temp = $contentList[$objId];
                    $temp['type'] = (int)$objType;
                    $temp['title'] = $v['obj_title'] ?? '';
                    $temp['pic_url'] = $v['pic_id'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $v['pic_id'],
                        ImgUrl::IMAGE_SIZE_OP_ORI) : '';
                    $temp['tags'] = $objType == BlockType::TYPE_PHOTO ? $v['obj_tag'] : (empty($v['obj_tag']) ? [] : explode(',',
                        $v['obj_tag']));
                    $moduleSpecialMap[$v['module_id']][] = $temp;
                }
            }
        }

        //内容id分组
        $contentMap = [];
        foreach ($moduleArticles as $key => $item) {
            $contentMap[$item['article_type']][] = $item['aid'];
        }
        foreach ($contentMap as $article_type => $aids) {
            $contentMap[$article_type] = AdmContent::dynamic($article_type, $aids, $uid);
        }

        //格式化卡片模块数据
        $moduleCardMap = [];
        if ($moduleArticles) {
            foreach ($moduleArticles as $v) {
                $aid = $v['aid'];
                $article_type = $v['article_type'];
                $contentList = $contentMap[$article_type] ?? [];
                if (isset($contentList[$aid])) {
                    $temp = $contentList[$aid];
                    $temp['type'] = intval($article_type);
                    $moduleCardMap[$v['module_id']][] = $temp;
                }
            }
        }

        //遍历处理每个模块
        foreach ($pageModules as $pageModule) {
            switch ($pageModule['type']) {
                case  mPageModule::MODULE_TYPE_IMG:
                    $itemImgs = isset($moduleImgsMap[$pageModule['id']]) ? $moduleImgsMap[$pageModule['id']] : [];
                    $response['module_list'][] = self::formatImgModule($pageModule, $itemImgs, $uid);
                    break;
                case  mPageModule::MODULE_TYPE_WIKI:
                    $itemWikis = isset($pageModuleWikisMap[$pageModule['id']]) ? $pageModuleWikisMap[$pageModule['id']] : [];
                    $response['module_list'][] = self::formatWikiModule($pageModule, $itemWikis, $wikiInfos);
                    break;
                case  mPageModule::MODULE_TYPE_GOODS:
                    $itemGoods = isset($pageModuleGoodsMap[$pageModule['id']]) ? $pageModuleGoodsMap[$pageModule['id']] : [];
                    $response['module_list'][] = self::formatGoodsModule($pageModule, $itemGoods, $goodsInfos);
                    break;
                case  mPageModule::MODULE_TYPE_ANCHOR:
                    $response['module_list'][] = self::formatAnchorModule($pageModule, $pageModules);
                    break;
                case  mPageModule::MODULE_TYPE_TAB:
                    $response['module_list'][] = self::formatTabModule($pageModule, $pageModules);
                    break;
                case  mPageModule::MODULE_TYPE_FLOAT:
                    $response['module_list'][] = self::formatFloatModule($pageModule);
                    break;
                case mPageModule::MODULE_TYPE_WATERFALL:
                    $response['module_list'][] = self::formatWaterfallModule($pageModule, $uid);
                    break;
                case mPageModule::MODULE_TYPE_FOLLOW:
                case mPageModule::MODULE_TYPE_DESIGNER:
                    $response['module_list'][] = self::formatFollowModule($pageModule, $uid);
                    break;
                case mPageModule::MODULE_TYPE_CARD_BANNER:
                    $itemImgs = isset($moduleImgsMap[$pageModule['id']]) ? $moduleImgsMap[$pageModule['id']] : [];
                    $response['module_list'][] = self::formatCardModule($pageModule, $uid, $itemImgs,
                        $itemArticles = []);
                    break;
                case mPageModule::MODULE_TYPE_CARD_ARTICLE:
                    $itemArticles = isset($moduleCardMap[$pageModule['id']]) ? $moduleCardMap[$pageModule['id']] : [];
                    $response['module_list'][] = self::formatCardModule($pageModule, $uid, $itemImgs = [],
                        $itemArticles);
                    break;
                case mPageModule::MODULE_TYPE_CARD_WATERFALL:
                    $itemArticles = isset($moduleCardMap[$pageModule['id']]) ? $moduleCardMap[$pageModule['id']] : [];
                    $response['module_list'][] = self::formatCardWaterfallModule($pageModule, $uid, $itemArticles);
                    break;
                case mPageModule::MODULE_TYPE_SPECIAL_ARTICLE:
                case mPageModule::MODULE_TYPE_SPECIAL_NOTE:
                    $itemArticles = isset($moduleSpecialMap[$pageModule['id']]) ? $moduleSpecialMap[$pageModule['id']] : [];

                    $ext = json_decode($pageModule['ext'], true);

                    $temp = [];
                    if ($itemArticles) {
                        foreach ($itemArticles as $v) {
                            $temp[] = $v;
                        }
                    }
                    $response['module_list'][] = [
                        'id' => $pageModule['id'],
                        'type' => $pageModule['type'],
                        'style' => $pageModule['style'],
                        'module' => [
                            'title' => $pageModule['title'],
                            'button_color' => $ext['button_color'] ?? '',
                            'list' => $temp,
                        ],
                    ];
                    break;
                case mPageModule::MODULE_TYPE_VIDEO:
                    $ext = json_decode($pageModule['ext'], true);
                    $response['module_list'][] = [
                        'id' => $pageModule['id'],
                        'type' => $pageModule['type'],
                        'style' => $pageModule['style'],
                        'module' => [
                            'title' => $pageModule['title'],
                            'link' => $ext['link'],
                            'pic_url' => ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $ext['pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI),
                        ],
                    ];
                    break;
                case mPageModule::MODULE_TYPE_SPECIAL_GOODS:
                    $itemGoods = $pageModuleGoodsMap[$pageModule['id']] ?? [];
                    $itemGoodsIds = empty($itemGoods) ? [] : array_column($itemGoods, 'goods_id');
                    $uids = empty($itemGoods) ? [] : array_column($itemGoods, 'uid');
                    $userInfo = empty($uids) ? [] : \Doraemon\service\User::getusers_baisic_info($uids);
                    $activityInfo = [
                        'activity_type' => ActivityInfo::ACTIVITY_TYPE_NORMAL,
                    ];
                    $activity = empty($itemGoodsIds) ? [] : AllactivityInfoBak::getActivityListByGoodsIds($itemGoodsIds,
                        $activityInfo);

                    $tempList = [];
                    foreach ($itemGoods as $itemGood) {
                        $goods_id = $itemGood['goods_id'] ?? 0;
                        $itemUserInfo = $userInfo[$itemGood['uid']] ?? [];
                        $activity_info = $activity[$goods_id]['starting'] ?? [];
                        $is_preview = isset($activity[$goods_id]['preview']) && empty($activity_info);
                        $activity_info = empty($activity_info) ? ($activity[$goods_id]['preview'] ?? []) : $activity_info;
                        $actual_stock = array_column($activity_info, 'actual_stock');
                        $activity_price = array_column($activity_info, 'activity_price');
                        $min_price = empty($activity_price) ? 0 : min($activity_price);
                        $tempGoodsInfo = $goodsInfos[$goods_id] ?? null;
                        $ori_min_price = isset($tempGoodsInfo) ? $tempGoodsInfo['ori_min_price'] : 0;
                        $actual_stock = array_sum($actual_stock);
                        $tempList[] = [
                            'goods_id' => $goods_id,
                            'activity' => $is_preview ? 'preview' : 'starting',
                            'goods_info' => $tempGoodsInfo,
                            'activity_info' => [
                                'actual_stock' => $actual_stock > 0 ? $actual_stock : $tempGoodsInfo['actual_stock'],
                                'activity_price' => $min_price > 0 ? $min_price : $ori_min_price,
                                'discount_price' => bcsub($ori_min_price, $min_price, 2),
                            ],
                            'describe' => $itemGood['goods_describe'],
                            'ext_info' => strlen($itemGood['goods_desc']) ? [
                                'text' => $itemGood['goods_desc'],
                                'icon' => empty($itemGood['discount_icon']) ? '' : ImgUrl::getUrl(ImgUrl::APPTYPE_OP,
                                    $itemGood['discount_icon'], ImgUrl::IMAGE_SIZE_OP_ORI),
                            ] : null,
                            'comment' => $itemGood['uid'] > 0 ? [
                                'nick' => $itemUserInfo['nick'] ?? '',
                                'avatar' => $itemUserInfo['avatar'] ?? '',
                                'comment' => $itemGood['user_comment'] ?? '',
                            ] : null,
                        ];
                    }
                    $response['module_list'][] = [
                        'id' => $pageModule['id'],
                        'title' => $pageModule['title'],
                        'type' => $pageModule['type'],
                        'style' => $pageModule['style'],
                        'module' => [
                            'list' => $tempList,
                        ],
                    ];
                    break;
                case mPageModule::MODULE_TYPE_GOODS_SET:
                    $list = self::formatGoodsSet($pageModule);
                    $response['module_list'][] = [
                        'id' => $pageModule['id'],
                        'title' => $pageModule['title'],
                        'type' => $pageModule['type'],
                        'style' => $pageModule['style'],
                        'module' => [
                            'total' => $list['num'],
                            'top_ids' => $list['top_ids'],
                            'wiki_ids' => $list['wiki_ids'],
                            'list' => $list['list'],
                            'bg_img' => ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $list['bg_img'], ImgUrl::IMAGE_SIZE_OP_ORI),
                        ],
                    ];
                    break;
                case mPageModule::MODULE_TYPE_MAP:
                    $response['module_list'][] = [
                        'id' => $pageModule['id'],
                        'type' => $pageModule['type'],
                        'module' => [
                            'title' => $pageModule['title'],
                            'total' => $list['num'],
                        ],
                    ];
                    break;
                case mPageModule::MODULE_TYPE_BLIND_BOX:
                    $ext = json_decode($pageModule['ext'], true);
                    $response['module_list'][] = [
                        'id' => $pageModule['id'],
                        'type' => $pageModule['type'],
                        'module' => [
                            'title' => $pageModule['title'],
                            'bg_img' => ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $ext['bg_img'], ImgUrl::IMAGE_SIZE_OP_ORI),
                            'btn_before' => ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $ext['btn_before'], ImgUrl::IMAGE_SIZE_OP_ORI),
                            'btn_after' => ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $ext['btn_after'], ImgUrl::IMAGE_SIZE_OP_ORI),
                        ],
                    ];
                    break;
                case mPageModule::MODULE_TYPE_MULTI_FOLLOW:
                    $ext = json_decode($pageModule['ext'], true);
                    $response['module_list'][] = [
                        'id' => $pageModule['id'],
                        'type' => $pageModule['type'],
                        'module' => [
                            'uid' => $uid,
                            'followed' => empty(self::$follow_uids) ? 1 : 0,
                            'follow_uids' => self::$follow_uids,
                            'button_img' => ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $ext['pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI),
                            'followed_button_img' => ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $ext['done_pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI),
                        ]
                    ];
                    break;


                case mPageModule::MODULE_TYPE_CPL:
                    $ext = json_decode($pageModule['ext'], true);
                    $response['module_list'][] = [
                        'id' => $pageModule['id'],
                        'type' => $pageModule['type'],
                        'style' => $pageModule['style'],
                        'module' => $moduleCpls[$pageModule['id']] ? :[]
                    ];
                    break;

                case mPageModule::MODULE_TYPE_SHOP_BOOK:
                    $ext = json_decode($pageModule['ext'], true);
                    $response['module_list'][] = [
                        'id' => $pageModule['id'],
                        'type' => $pageModule['type'],
                        'module' => [
                            'title' => $pageModule['title'],
                            'pic_url' => ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $ext['pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI),
                            'shop_id' => $ext['shop_id'],
                        ],
                    ];
                    break;

            }
        }

        //关联活动id处理
        if ($relationPageInfo) {
            $maxGoods = 3;
            foreach ($relationPageInfo as $info) {
                $list = isset($moduleGoodsMap[$info['id']]) ? array_slice($moduleGoodsMap[$info['id']], 0,
                    $maxGoods) : [];
                foreach ($list as $key => $goods) {
                    if (isset($goodsInfos[$goods['goods_id']])) {
                        $list[$key] = array_merge($goodsInfos[$goods['goods_id']],
                            ['goods_desc' => $goods['goods_desc']]);
                    }
                }
                $response['module_list'][] = [
                    'id' => '0',
                    'page_id' => $info['id'],
                    'cover_img_big_url' => $info['cover_img_big_url'],
                    'type' => mPageModule::MODULE_TYPE_RELATION,
                    'style' => '3',
                    'list' => $list,
                ];
            }
        }
        return $response;
    }

    /**
     * 好物集合数据格式化
     * @param $moduleInfo
     * @return array
     * @throws \Exception
     */
    private static function formatGoodsSet($moduleInfo)
    {
        $ext = $moduleInfo ? json_decode($moduleInfo['ext'], true) : '';
        $bg_img = $ext ? $ext['bg_img'] : '';
//        $top_ids = $ext['topic_ids'] ? explode(",", $ext['topic_ids']) : [];
        $top_ids = $ext['topic_ids'] ?: 0;
        
        $cache_wiki_ids = TopicWiki::getAllWikiIds($top_ids);
        
        $wiki_ids_set = $moduleInfo['ext'] ? json_decode($moduleInfo['ext'], true) : [];
        $wiki_ids = $wiki_ids_set['top_wiki_ids'];
        //获取预设wiki
        $wiki_ids = explode(',', $wiki_ids);
        
        $all_wiki_ids = array_merge($wiki_ids, $cache_wiki_ids);

        //预设wiki数量
        $wiki_total = count($all_wiki_ids);
        $wiki_ids_four = array_slice($all_wiki_ids, 0, 4);
        $list = Wiki::getWikiBaseList($wiki_ids_four);
        $img_list = array_column($list, 'cover_img', 'id');

        $data['list'] = $img_list ? array_values($img_list) : [];
        $data['num'] = $wiki_total;
        $data['bg_img'] = $bg_img;
        $data['top_ids'] = $top_ids;
        $data['wiki_ids'] = $wiki_ids;
        return $data;
    }

    private static function formatImgModule($moduleInfo, $moduleImgs, $uid)
    {
        $formatModule = [
            'id' => $moduleInfo['id'],
            'type' => $moduleInfo['type'],
            'sytle' => $moduleInfo['style']
        ];
    
        foreach ($moduleImgs as $img) {
            $params = $img['link_params'] ? json_decode($img['link_params'], true) : [];
            $coupon_id = in_array($img['link_type'], [
                'coupon',
                'coupon_status'
            ]) ? $params : "";
            $link = LinkFormat::generateLink($img['link_type'], $img['link_params']);
            $temp = [
                'id' => $img['id'],
                'img_url' => $img['img_url'],
                'link_url' => $link['mini_program_template'] ?: $link['app_template'],
                'out_link' => $link['mobile_template'] ?: '',
                'coupon_id' => $coupon_id['coupon_id'] ?? '',
            ];
        
            if ($img['link_type'] == 'h5_hit_list') {
                $temp['wiki_id'] = $params['wiki_id'] ?? 0;
            }
            //优惠券状态 $uid
            if ($img['link_type'] == 'coupon_status') {
                $temp['tag'] = self::couponTag($coupon_id, $uid);
            }
            $formatModule['list'][] = $temp;
        }
        return $formatModule;
    }

    private static function couponTag($coupon_id, $uid)
    {
        $tag = self::COUPON_TAG_NONE;
        if ($uid) {
            //登录查询是否领取
            $tag = Coupon::getUserHasCouponSum($coupon_id, $uid) ? self::COUPON_TAG_RECEIVED : self::COUPON_TAG_NONE;
        }
        if ($tag === self::COUPON_TAG_NONE) {
            $tag = Coupon::getCouponReceived($coupon_id) ? self::COUPON_TAG_OVER : self::COUPON_TAG_NONE;
        }
        return $tag;
    }

    private static function formatGoodsModule($moduleInfo, $moduleGoods, $goodsInfos)
    {
        $formatModule = [
            'id' => $moduleInfo['id'],
            'type' => $moduleInfo['type'],
            'sytle' => $moduleInfo['style']
        ];
        foreach ($moduleGoods as $goods) {
            if (isset($goodsInfos[$goods['goods_id']])) {
                $formatModule['list'][] = array_merge($goodsInfos[$goods['goods_id']],
                    ['goods_desc' => $goods['goods_desc']]);
            }
        }
        return $formatModule;
    }

    private static function formatWikiModule($moduleInfo, $moduleWikis, $wikiInfos)
    {
        $ext = json_decode($moduleInfo['ext'], true);
        $formatModule = [
            'id' => $moduleInfo['id'],
            'type' => $moduleInfo['type'],
            'sytle' => $moduleInfo['style'],
            'jump' => $ext['jump'] ?? 1
        ];
        foreach ($moduleWikis as $wiki) {
            if (isset($wikiInfos[$wiki['wiki_id']])) {
                $formatModule['list'][] = array_merge($wikiInfos[$wiki['wiki_id']],
                    ['wiki_desc' => $wiki['wiki_desc']]);
            }
        }
        return $formatModule;
    }


    /**
     * @param $moduleInfo
     * @param $self_uid
     * @return array
     */
    public static $follow_uids = [];
    private static function formatFollowModule($moduleInfo, $self_uid)
    {
        $ext = json_decode($moduleInfo['ext'], true);

        $uid = $ext['uid'];
        $link_type = $ext['link_type'] ?? '';
        $custom_title = $ext['custom_title'] ?? '';
        $custom_img = $ext['custom_img'] ?? '';
        $button_color = $ext['button_color'] ?? '';
        $text_color = $ext['text_color'] ?? '';
        $link_params = $ext['link_params'] ?? '';
        $link_params = json_decode($link_params, true);
        $objRs = BlockTypeMapping::getObjFromLinkParams($link_type, $link_params);
        $obj_id = $objRs['obj_id'] ?? null;
        $obj_type = $objRs['obj_type'] ?? null;
        $content = AdmContent::dynamic($obj_type, [$obj_id], $self_uid);
        $content = $content[$obj_id] ?? [];
        //替换标题和图片
        if (isset($content['article_info'])) {
            if ($custom_title) $content['article_info']['title'] = $custom_title;
            if ($custom_img) $content['article_info']['cover_pic_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $custom_img, ImgUrl::IMAGE_SIZE_OP_ORI);
        }
        if (isset($content['blank_info'])) {
            if ($custom_title) $content['blank_info']['title'] = $custom_title;
            if ($custom_img) $content['blank_info']['cover_pic_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $custom_img, ImgUrl::IMAGE_SIZE_OP_ORI);
        }
        if (isset($content['guide_info'])) {
            if ($custom_title) $content['guide_info']['title'] = $custom_title;
            if ($custom_img) $content['guide_info']['cover_pic_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $custom_img, ImgUrl::IMAGE_SIZE_OP_ORI);
        }
        //关注按钮颜色
        $button = null;
        if ($button_color) $button['button_color'] = $button_color;
        if ($text_color) $button['text_color'] = $text_color;

        $usersInfo = \Doraemon\service\User::getUsers([$uid]);
        $userInfo = $usersInfo[$uid] ?? [];
        //查询用户是否关注
        $isFollow = Follow::isFollowedMulti($self_uid, [$uid]);
        //官方账号 type:5 和 普通账号 type:0  头像、昵称、签名（若无则不展示
        //设计师/设计机构 type:2 头像、昵称、设计费、所在城市
        //品牌 type: 1 头像、昵称、品牌简介

        $user_counter = UserCounter::getOne($uid);

        if (empty($isFollow[$uid])) self::$follow_uids[] = $uid;

        //公用用户信息
        $userObj = [
            'uid' => $uid,
            'nick' => $userInfo['nick'] ?? '',
            'type' => $userInfo['type'] ?? '',
            'sub_type' => $userInfo['sub_type'] ?? '',
            'avatar' => $userInfo['avatar'] ?? '',
            'isFollow' => isset($isFollow[$uid]) && $isFollow[$uid] > 0,
            'fans' => $user_counter['fans'],
        ];
        switch ($userInfo['type']) {
            case Member::AUTH_USER_BRAND:
                //品牌信息
                $brand_info = \Biz\service\brand\Brand::getBrandInfosByUid($uid, ["discription", "brand_type", 'id']);
                $brand_id = $brand_info[0]['id'] ?: 0;
                $user_like = BrandBeLikedache::getUserLike($brand_id);
                $user_like += $user_counter['beliked'] + $user_counter['befavorited'];
                $user_counter['user_like'] = $user_like;
                
                $userObj['detail'] = $brand_info[0]['discription'];
                $userObj['brand_type'] = $brand_info[0]['brand_type'];
                $userObj['total'] = $user_counter['liver_said'];
                $userObj['user_like'] = $user_counter['user_like'];
                break;
            case Member::AUTH_USER_DESIGNER:
                $full = \Doraemon\service\User::getUserInfo($uid);
                $userObj['service_area'] = $full['service_area'] ?? ''; //所在城市
                $userObj['price_range'] = $full['price_range'] ?? ''; //设计费
                $userObj['total'] = $user_counter['follow'];
                break;
            default:
                $userObj['total'] = $user_counter['beliked'] + $user_counter['befavorited'];
                $userObj['profile'] = $userInfo['profile'] ?? '';
                break;
        }
        $pic_base_img = $ext['card_info']['pic_base_id'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $ext['card_info']['pic_base_id'],
            ImgUrl::IMAGE_SIZE_OP_ORI) : '';
        $pic_bg_img = $ext['card_info']['pic_bg_id'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $ext['card_info']['pic_bg_id'],
            ImgUrl::IMAGE_SIZE_OP_ORI) : '';
        $formatModule = [
            'id' => $moduleInfo['id'],
            'type' => $moduleInfo['type'],
            'style' => $moduleInfo['style'],
            'module' => [
                'title' => $moduleInfo['title'],
                'user_info' => $userObj,
                'content' => empty($content) ? null : $content,
                'bgcolor' => &self::$floatBgColor,
                'pic_base_id' => $pic_base_img,
                'pic_bg_id' => $pic_bg_img,
                'name_color' => $ext['card_info']['name_color'] ? (int)$ext['card_info']['name_color'] : 1,
                'content_color' => $ext['card_info']['content_color'] ? (int)$ext['card_info']['content_color'] : 1,

            ],
            'button' => $button,
        ];
        return $formatModule;
    }

    /**
     * @param $moduleInfo
     * @param $moduleImgs
     * @return array
     */
    private static function formatCardModule($moduleInfo, $uid, $moduleImgs, $moduleArticles)
    {
        $cardType = $moduleInfo['type'];

        //banner模块处理
        $list = [];
        if ($cardType == mPageModule::MODULE_TYPE_CARD_BANNER) {
            $i = 1;
            foreach ($moduleImgs as $img) {
                $coupon_id = in_array($img['link_type'], [
                    'coupon',
                    'coupon_status'
                ]) ? $img['link_params'] : "";
                $link = LinkFormat::generateLink($img['link_type'], $img['link_params']);
                $temp = [
                    'id' => $img['id'],
                    'img_url' => $img['img_url'],
                    'link_url' => $link['app_template'],
                    'out_link' => $link['mobile_template'],
                    'coupon_id' => $coupon_id,
                    "statSign" => StatSign::getStatSignForAd(StatSign::H5_ACTIVITY_BANNER, intval($img['id']), $idx = $i, 0)
                ];
                //优惠券状态 $uid
                if ($img['link_type'] == 'coupon_status') {
                    $temp['tag'] = self::couponTag($coupon_id, $uid);
                }
                $list[] = $temp;
                $i++;
            }
        } else {
            $list = $moduleArticles;
        }

        $formatModule = [
            'id' => $moduleInfo['id'],
            'title' => $moduleInfo['title'],
            'type' => $moduleInfo['type'],
            'style' => $moduleInfo['style'],
            'module' => [
                'cardType' => $cardType,
                'list' => $list,
            ],
        ];

        return $formatModule;
    }

    /**
     * @param $moduleInfo
     * @param $uid
     * @param $moduleArticles
     * @return array
     */
    private static function formatCardWaterfallModule($moduleInfo, $uid, $moduleArticles)
    {
        $cardType = $moduleInfo['type'];
        $list = $moduleArticles;

        $formatModule = [
            'id' => $moduleInfo['id'],
            'title' => $moduleInfo['title'],
            'type' => $moduleInfo['type'],
            'style' => $moduleInfo['style'],
            'module' => [
                'cardType' => $cardType,
                'list' => $list,
            ],
        ];

        return $formatModule;
    }

    /**
     * @param $moduleInfo
     * @param $uid
     * @return array
     */
    private static function formatWaterfallModule($moduleInfo, $uid)
    {
        $ext = json_decode($moduleInfo['ext'], true);
        $topicIds = is_array($ext['topic_id']) ? $ext['topic_id'] : explode(",", $ext['topic_id']);
        $uniqueTopicIds = [];
        foreach ($topicIds as $topicId) {
            $topicInfo = explode(PageModule::MODULE_WATERFALL_TAB_DELIMITER, $topicId);
            $uniqueTopicIds[] = $topicInfo[0];
        }
        $uniqueTopicIds = array_unique($uniqueTopicIds);
        $join = 0;
        foreach ($uniqueTopicIds as $v) {
            $join += Topic::getItem($v);
        }

        $formatModule = [
            'id' => $moduleInfo['id'],
            'type' => PageModule::MODULE_TYPE_WATERFALL,
            'style' => $moduleInfo['style'],
            'module' => [
                'title' => $moduleInfo['title'],
                'is_show_num' => $ext['is_show_num'],
                'join' => (int)($join > 0 ? $join : 0),
                'topic_id' => implode($topicIds, ','),
            ],
        ];
        return $formatModule;
    }

    /**
     * @param $moduleInfo
     * @return array
     */
    private static function formatFloatModule($moduleInfo)
    {
        $ext = json_decode($moduleInfo['ext'], true);
        self::$floatBgColor = $ext['bgcolor'];
        $link = LinkFormat::generateLink($ext['link_type'],
            is_array($ext['link_params']) ? json_encode($ext['link_params']) : $ext['link_params']);
        $formatModule = [
            'id' => $moduleInfo['id'],
            'type' => $moduleInfo['type'],
            'style' => $moduleInfo['style'],
            'module' => [
                'title' => $moduleInfo['title'],
                'bgcolor' => self::$floatBgColor,
                'link_url' => $link['app_template'],
                'out_link' => $link['mobile_template'],
            ],
        ];
        return $formatModule;
    }

    /**
     * @param $moduleInfo
     * @param $pageModules
     * @return array
     */
    private static function formatTabModule($moduleInfo, $pageModules)
    {
        $formatModule = [
            'id' => $moduleInfo['id'],
            'type' => $moduleInfo['type'],
            'sytle' => $moduleInfo['style']
        ];
        $hasActive = false;
        foreach ($pageModules as $key => $pageModule) {
            if ($pageModule['tab']) {
                $start = strtotime($pageModule['start_time']) <= time();
                $end = strtotime($pageModule['end_time']) >= time();
                $active = 0;
                if ($start && $end) {
                    $active = $hasActive ? 0 : 1;
                    $hasActive = true;
                }
                $formatModule['list'][] = [
                    'id' => $pageModule['id'],
                    'title' => $pageModule['tab'],
                    'active' => $active,
                ];
                $pageModules[$key] = $pageModule;
            }
        }
        $firstActive = false;
        if (!$hasActive) {
            unset($formatModule['list']);
            foreach ($pageModules as $key => $pageModule) {
                if ($pageModule['tab']) {
                    $active = 0;
                    if (!$firstActive) {
                        $active = 1;
                        $firstActive = true;
                    }
                    $formatModule['list'][] = [
                        'id' => $pageModule['id'],
                        'title' => $pageModule['tab'],
                        'active' => $active,
                    ];
                    $pageModules[$key] = $pageModule;
                }
            }
        }
        self::$follow_uids = [];
        return $formatModule;
    }

    private static function formatAnchorModule($moduleInfo, $pageModules)
    {
        $ext = json_decode($moduleInfo['ext'], true);
        $bg_color = $ext['bg_color'] ?? '';
        $text_color = $ext['text_color'] ?? '';
        $formatModule = [
            'id' => $moduleInfo['id'],
            'type' => $moduleInfo['type'],
            'active' => compact('bg_color', 'text_color'),
            'sytle' => $moduleInfo['style']
        ];
        foreach ($pageModules as $pageModule) {
            if ($pageModule['anchor']) {
                $formatModule['list'][] = [
                    'id' => $pageModule['id'],
                    'title' => $pageModule['anchor']
                ];
            }
        }
        return $formatModule;
    }

    private static function formatShareInfo($pageInfo)
    {
        if ($pageInfo['share_title']) {
            $shareUrl = BizUrl::h5ActivityPage($pageInfo['id']);
            return [
                'wechat' => [
                    'title' => $pageInfo['share_title'],
                    'desc' => $pageInfo['share_desc'],
                    'cover_img' => $pageInfo['share_img_url'],
                    'url' => $shareUrl
                ],
                'wechat_moments' => [
                    'title' => $pageInfo['share_title'],
                    'cover_img' => $pageInfo['share_img_url'],
                    'url' => $shareUrl
                ],
                'weibo' => [
                    'title' => $pageInfo['share_title'] . " " . $shareUrl,
                    'cover_img' => $pageInfo['share_img_url'],
                    'url' => $shareUrl
                ],
                'qq' => [
                    'title' => $pageInfo['share_title'],
                    'desc' => $pageInfo['share_desc'],
                    'cover_img' => $pageInfo['share_img_url'],
                    'url' => $shareUrl
                ],
            ];
        } else {
            return null;
        }
    }

    public static function admGetModuleList($pageId)
    {
        $pageInfo = mPage::getPageInfoById($pageId);
        $pageModules = mPageModule::getModuleListByPageId($pageId);
        foreach ($pageModules as &$pageModule) {
            if (strtotime($pageModule['start_time']) < 0) {
                $pageModule['start_time'] = $pageInfo['start_time'];
            }
            if (strtotime($pageModule['end_time']) < 0) {
                $pageModule['end_time'] = $pageInfo['end_time'];
            }
        }
        return $pageModules;
    }

    /**
     * @desc 商城小程序首页[你可能也喜欢]
     */
    public static function getMiniActive()
    {
        $list = mPage::getList([
            'mini_status' => mPage::STATUS_NORMAL,
            'end_time[>]' => date('Y-m-d H:i:s'),
            'start_time[<]' => date('Y-m-d H:i:s'),
        ]);
        $pageIds = $list ? array_column($list, 'id') : [];
        $goods = self::getPageGoods($pageIds);
        $response = [];
        if ($list) {
            foreach ($list as $value) {
                $temp = [
                    'id' => $value['id'],
                    'url' => $value['url'],
                    'special_info_img' => $value['cover_img_big_url'],
                    'goods' => isset($goods[$value['id']]) ? array_slice($goods[$value['id']]['goods'], 0, 3) : []
                ];
                $response[] = $temp;
            }
        }
        return $response;
    }

    public static function pageModuleTopicCounter($topicId = 0)
    {
        if ($topicId > 0) {
            $topic_ids = [$topicId];
        } else {
            //todo 查询活动页中瀑布流数据
            $list = mPageModule::select('*', $where = [
                'type' => mPageModule::MODULE_TYPE_WATERFALL,
                'status' => mPageModule::STATUS_NORMAL,
            ]);
            $topic_ids = empty($list) ? [] : array_map(function ($v) {
                $ext = json_decode($v['ext'], true);
                $topic_id = $ext['topic_id'] ?? [];
                if (is_scalar($topic_id)) $topic_id = explode(',', $topic_id);
                return array_filter($topic_id);
            }, $list);
            $unique_topic_ids = [];
            foreach ($topic_ids as $v) {
                foreach ($v as $vv) {
                    $temp = explode(\Biz\model\activity\PageModule::MODULE_WATERFALL_TAB_DELIMITER, $vv);
                    $unique_topic_id = trim(current($temp));
                    $unique_topic_ids[$unique_topic_id] = $unique_topic_id;
                }
            }
            $topic_ids = $unique_topic_ids;
        }

        //todo 获取话题被关注数
        //todo 获取话题下的note
        if ($topic_ids) {
            $topicMap = [];
            $pageSize = 500;
            foreach ($topic_ids as $topic_id) {
                $topicTotal = 0;
                $topicCount = \Doraemon\cache\TopicCounter::getOne($topic_id);
                $topicFollow = $topicCount['follow'] ?? 0;

                $extraParams = array(
                    'topic_activity_id' => $topic_id,
                );
                $scrollId = '';
                $noteIds = [];
                while (true) {
                    $solrResult = Photos::scrollAnswer($topic_id, $pageSize, $scrollId);
                    $ids = $solrResult['rows'] ?? [];
                    $scrollId = !empty($solrResult['scroll_id']) ? $solrResult['scroll_id'] : $scrollId;
                    if (empty($ids)) {
                        if ($scrollId) {
                            EsPhoto::clearScroll($scrollId);
                        }
                        break;
                    }
                    $noteIds = array_merge($noteIds, $ids);
                }
                $photoCount = \Doraemon\cache\PhotoCounter::getMulti($noteIds);
                foreach ($photoCount as $count) {
                    $topicTotal += $count['comment'] ?? 0;
                    $topicTotal += $count['like'] ?? 0;
                    $topicTotal += $count['favorite'] ?? 0;
                }
                $topicMap[$topic_id] = $topicTotal + $topicFollow;
                \Doraemon\tools\Log::debug('活动页中数量统计',
                    compact('topic_id', 'topicFollow', 'noteIds', 'photoCount', 'topicTotal'));
            }
            //设置缓存
            Topic::setItems($topicMap);
        }
    }
}